package com.str.queue;
public class ArrayQueue implements Queue {

  private static final int DEFAULT_SIZE = 10;
  private Object[] array; // holds the data stored in the queue
  private int front;  // index of first item in the queue
  private int rear;   // index of the next cell for enqueue
  private int count;  // number of items in the queue

// Constructor       
  public ArrayQueue() {
    array = new Object[DEFAULT_SIZE];
    front = rear = count = 0; 
  }

// Modifiers
  public void clear() {
    for (int i = 0; i < array.length; i++)
      array[i] = null;
    front = rear = count = 0;
  }

  public void enqueue(Object val) { 
    if (count == array.length) expand();
    array[rear++] = val; 
    if (rear == array.length) rear = 0; 
    count++; 
  }

  public Object dequeue() { 
    if (count == 0)
      throw new IllegalStateException();
    Object val = array[front];
    array[front++] = null;
    if (front == array.length) front = 0;
    count--;
    return val;
  }

// Accessors
  public boolean isEmpty() { return count == 0; }

  public int size() { return count; }

  public Object peek() { 
    if (count == 0)
      throw new IllegalStateException();
    return array[front];
  }

// Auxiliary methods
  private void expand() {
  	Object[] newArray = new Object[2 * array.length];
  	for (int i = 0; i < array.length; i++)
  	  newArray[i] = array[(front+i) % array.length];
  	front = 0;
    rear = array.length;
    array = newArray;
  }		

  // Returns a string representation of the queue
  public String toString() { 
    String buf = new String("[ ");
    for (int i = 0; i < count; i++) {
      if (i > 0) buf += ", ";    
      buf += array[(front+i) % array.length].toString();
    }
    buf += " ]";
    return buf;
  }
}
